package com.asdan.seededu.web.controller;


import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.asdan.seededu.alipay.util.httpClient.HttpRequest;
import com.asdan.seededu.front.service.WyefService;
import com.asdan.seededu.front.service.impl.Product01ServiceImp;
import com.asdan.seededu.front.service.impl.WyefServiceImp;
import com.asdan.seededu.service.AlipayService;
import com.asdan.seededu.service.impl.AlipayServiceImpl;
import com.asdan.seededu.util.Calenda;
import com.demo2do.core.web.interceptor.MenuSetting;

@Controller
@MenuSetting("menu-data")
@RequestMapping("alipay")
public class AlipayController {

	@RequestMapping(value="",method=RequestMethod.GET)
	public String Alipay() {
		return "alipay";
	}

	@RequestMapping(value="/notify",method=RequestMethod.GET,produces="text/html;charset=UTF-8")
	public ModelAndView alipayNotifyGET(String body,String buyer_email,String buyer_id,String discount,
			String gmt_create,String gmt_logistics_modify,String gmt_payment,String is_success,
			String is_total_fee_adjust,String logistics_fee,String logistics_payment,String logistics_type
			,String notify_id,String notify_time,String notify_type,String out_trade_no,String payment_type,
			String price,String quantity,String receive_address,String receive_mobile,String receive_name,
			String receive_phone,String receive_zip,String seller_actions,String seller_email,
			String seller_id,String subject,String total_fee,String trade_no,String trade_status,
			String use_coupon,String sign,String sign_type,HttpServletRequest req) {
		try{
			Calenda cal = new Calenda();
			AlipayService as = new AlipayServiceImpl();
			String uid =(String)req.getSession().getAttribute("userid") ;

			String oid = req.getParameter("oid").toString();
			
			as.InsertOrderReply(oid,uid,body, buyer_email, buyer_id, discount, gmt_create, gmt_logistics_modify, gmt_payment, is_success, is_total_fee_adjust, logistics_fee, logistics_payment, logistics_type, price, quantity, receive_address, receive_mobile, receive_name, receive_phone, receive_zip, seller_actions, seller_email, seller_id, subject, total_fee, trade_no, trade_status, use_coupon, sign, sign_type, cal.getNowTime().toString());
			//System.out.println(uid);
			//获取支付宝的通知返回参数，
			//商户订单号

			//@SuppressWarnings("unused")
			//String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

			//支付宝交易号

			//@SuppressWarnings("unused")
			//String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

			//交易状态
			//String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

			//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

			//if(AlipayNotify.verify(params)){//验证成功
			
			if(is_success.equals("T")) {
				//请在这里加上商户的业务逻辑程序代码
				//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
				if(trade_status.equals("WAIT_BUYER_PAY")){
					//该判断表示买家已在支付宝交易管理中产生了交易记录，但没有付款
					//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
					return new ModelAndView("redirect:/userInfo/"+uid+"/userProInfo?message=yes");	//请不要修改或删除
				} else if(trade_status.equals("WAIT_SELLER_SEND_GOODS")){
					//该判断表示买家已在支付宝交易管理中产生了交易记录且付款成功，但卖家没有发货
					//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
					return new ModelAndView("redirect:/userInfo/"+uid+"/userProInfo?message=yes");//请不要修改或删除
				} else if(trade_status.equals("WAIT_BUYER_CONFIRM_GOODS")){
					//该判断表示卖家已经发了货，但买家还没有做确认收货的操作

					//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序

					return new ModelAndView("redirect:/userInfo/"+uid+"/userProInfo?message=yes");//请不要修改或删除
				} else if(trade_status.equals("TRADE_FINISHED")){
					//该判断表示买家已经确认收货，这笔交易完成

					//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
					return new ModelAndView("redirect:/userInfo/"+uid+"/userProInfo?message=yes");	//请不要修改或删除
				}
				else {
					return new ModelAndView("redirect:/userInfo/"+uid+"/userProInfo?message=yes");	//请不要修改或删除
				}

			}else{//验证失败
						return new ModelAndView("redirect:/order/wyeforder?message=no");
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return new ModelAndView("redirect:/pay/order.jsp");
	}
	
	@RequestMapping(value="/returndata",method=RequestMethod.GET,produces="text/html;charset=UTF-8")
	public ModelAndView alipayReturnGET(String body,String buyer_email,String buyer_id,String discount,
			String gmt_create,String gmt_logistics_modify,String gmt_payment,String is_success,
			String is_total_fee_adjust,String logistics_fee,String logistics_payment,String logistics_type
			,String notify_id,String notify_time,String notify_type,String out_trade_no,String payment_type,
			String price,String quantity,String receive_address,String receive_mobile,String receive_name,
			String receive_phone,String receive_zip,String seller_actions,String seller_email,
			String seller_id,String subject,String total_fee,String trade_no,String trade_status,
			String use_coupon,String sign,String sign_type,HttpServletRequest request) {
		try {
			Calenda cal = new Calenda();
			AlipayService as = new AlipayServiceImpl();
			String uid =(String)request.getSession().getAttribute("userid") ;
			String oid = request.getParameter("oid").toString();
			as.InsertOrderReply(oid,uid,body, buyer_email, buyer_id, discount, gmt_create, gmt_logistics_modify, gmt_payment, is_success, is_total_fee_adjust, logistics_fee, logistics_payment, logistics_type, price, quantity, receive_address, receive_mobile, receive_name, receive_phone, receive_zip, seller_actions, seller_email, seller_id, subject, total_fee, trade_no, trade_status, use_coupon, sign, sign_type, cal.getNowTime().toString());
			//response.setContentType("text/html;charset=UTF-8");
			//获取支付宝POST过来反馈信息
			//Map<String,String> params = new HashMap<String,String>();
			//System.out.println(uid);
			//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表//
			//商户订单号

			//交易状态
			//trade_status = new String(trade_status.getBytes("ISO-8859-1"),"UTF-8");
			//is_success = new String(is_success.getBytes("ISO-8859-1"),"UTF-8");

			//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表//

			//计算得出通知验证结果
			//boolean verify_result = AlipayNotify.verify(params);

			if(is_success.equals("T")){//验证成功
				//请在这里加上商户的业务逻辑程序代码

				//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

				if(trade_status.equals("WAIT_SELLER_SEND_GOODS")){
					//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
					
					//向user-data中写数据,表明将用户加入到子项目中. by ysb
					WyefService wfs=new WyefServiceImp();
					Product01ServiceImp ps = new Product01ServiceImp();
					int spid = ps.getSpidbyOid(Integer.parseInt(oid));
					int stepid[] = ps.getStepidbySpid(spid);
					wfs.CreateUserData(Integer.parseInt(uid), spid, stepid[0]);
					
					return new ModelAndView("redirect:/userInfo/userProInfo?message=yes");	
				}
				//该页面可做页面美工编辑
				
				//向user-data中写数据,表明将用户加入到子项目中. by ysb
				WyefService wfs=new WyefServiceImp();
				Product01ServiceImp ps = new Product01ServiceImp();
				int spid = ps.getSpidbyOid(Integer.parseInt(oid));
				int stepid[] = ps.getStepidbySpid(spid);
				wfs.CreateUserData(Integer.parseInt(uid), spid, stepid[0]);
				return new ModelAndView("redirect:/userInfo/userProInfo?message=yes");	
				//——请根据业务逻辑来编写程序——
			}else{
				//该页面可做页面美工编辑
				return new ModelAndView("redirect:/userInfo/userProInfo?message=no");
			}
		}catch (Exception e) {
			// TODO: handle exception\
			e.printStackTrace();
		}
		return new ModelAndView("redirect:/userInfo/userProInfo?message=exception2");
	}

	@RequestMapping(value="/notify",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	public ModelAndView alipayNotifyPOST(String body,String buyer_email,String buyer_id,String discount,
			String gmt_create,String gmt_logistics_modify,String gmt_payment,String is_success,
			String is_total_fee_adjust,String logistics_fee,String logistics_payment,String logistics_type
			,String notify_id,String notify_time,String notify_type,String out_trade_no,String payment_type,
			String price,String quantity,String receive_address,String receive_mobile,String receive_name,
			String receive_phone,String receive_zip,String seller_actions,String seller_email,
			String seller_id,String subject,String total_fee,String trade_no,String trade_status,
			String use_coupon,String sign,String sign_type,HttpServletRequest request) {
		try{
			alipayNotifyGET(body,buyer_email,buyer_id,discount,
					gmt_create,gmt_logistics_modify,gmt_payment,is_success,
					is_total_fee_adjust,logistics_fee,logistics_payment,logistics_type
					,notify_id,notify_time,notify_type,out_trade_no,payment_type,
					price,quantity,receive_address,receive_mobile,receive_name,
					receive_phone,receive_zip,seller_actions,seller_email,
					seller_id,subject,total_fee,trade_no,trade_status,
					use_coupon,sign,sign_type,request);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return new ModelAndView("redirect:/pay/order.jsp");
	}

	@RequestMapping(value="/returndata",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	public ModelAndView alipayReturnPOST(String body,String buyer_email,String buyer_id,String discount,
			String gmt_create,String gmt_logistics_modify,String gmt_payment,String is_success,
			String is_total_fee_adjust,String logistics_fee,String logistics_payment,String logistics_type
			,String notify_id,String notify_time,String notify_type,String out_trade_no,String payment_type,
			String price,String quantity,String receive_address,String receive_mobile,String receive_name,
			String receive_phone,String receive_zip,String seller_actions,String seller_email,
			String seller_id,String subject,String total_fee,String trade_no,String trade_status,
			String use_coupon,String sign,String sign_type,HttpServletRequest request) {
		try {
			alipayReturnGET(body,buyer_email,buyer_id,discount,
					gmt_create,gmt_logistics_modify,gmt_payment,is_success,
					is_total_fee_adjust,logistics_fee,logistics_payment,logistics_type
					,notify_id,notify_time,notify_type,out_trade_no,payment_type,
					price,quantity,receive_address,receive_mobile,receive_name,
					receive_phone,receive_zip,seller_actions,seller_email,
					seller_id,subject,total_fee,trade_no,trade_status,
					use_coupon,sign,sign_type,request);
		}catch (Exception e) {
			// TODO: handle exception\
			e.printStackTrace();
		}
		return new ModelAndView("redirect:/pay/order.jsp");
	}
	

	/*@SuppressWarnings("deprecation")
	@RequestMapping(value="/add",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	public @ResponseBody
	String AddAlipay(String uid,String out_trade_no,String subject,String price,String body,
			String show_url,String receive_name,String receive_address,String receive_zip,
			String receive_phone,String receive_mobile) {
		try{
			uid = "1";
			Calenda cal = new Calenda();
			out_trade_no = String.valueOf(cal.getNowTime().getYear()) + String.valueOf(cal.getNowTime().getMonth())+String.valueOf(cal.getNowTime().getDate())+
					String.valueOf(cal.getNowTime().getHours()) + String.valueOf(cal.getNowTime().getMinutes()) + String.valueOf(cal.getNowTime().getSeconds())+
					out_trade_no;
			AlipayService as = new AlipayServiceImpl();
			//response.setContentType("text/html;charset=UTF-8");
			//订单号
			//out_trade_no = new String(out_trade_no.getBytes("ISO-8859-1"),"UTF-8");
			//商户网站订单系统中唯一订单号，必填

			//订单名称
			//subject = new String(subject.getBytes("ISO-8859-1"),"UTF-8");
			//必填

			//付款金额
			//price = new String(price.getBytes("ISO-8859-1"),"UTF-8");
			//必填

			//商品数量
			String quantity = "1";
			//必填，建议默认为1，不改变值，把一次交易看成是一次下订单而非购买一件商品
			//物流费用
			String logistics_fee = "0.00";
			//必填，即运费
			//物流类型
			String logistics_type = "EXPRESS";
			//必填，三个值可选：EXPRESS（快递）、POST（平邮）、EMS（EMS）
			//物流支付方式
			String logistics_payment = "SELLER_PAY";
			//必填，两个值可选：SELLER_PAY（卖家承担运费）、BUYER_PAY（买家承担运费）
			//订单描述

			//body = new String(body.getBytes("ISO-8859-1"),"UTF-8");
			//商品展示地址
			//show_url = new String(show_url.getBytes("ISO-8859-1"),"UTF-8");
			//需以http://开头的完整路径，如：http://www.商户网站.com/myorder.html

			//收货人姓名
			//receive_name = new String(receive_name.getBytes("ISO-8859-1"),"UTF-8");
			//如：张三

			//收货人地址
			//receive_address = new String(receive_address.getBytes("ISO-8859-1"),"UTF-8");
			//如：XX省XXX市XXX区XXX路XXX小区XXX栋XXX单元XXX号
			receive_address = "北京市海淀区";

			//收货人邮编
			//receive_zip = new String(receive_zip.getBytes("ISO-8859-1"),"UTF-8");
			//如：123456
			receive_zip = "100011";

			//收货人电话号码
			//receive_phone = new String(receive_phone.getBytes("ISO-8859-1"),"UTF-8");
			//如：0571-88158090

			//收货人手机号码
			//receive_mobile = new String(receive_mobile.getBytes("ISO-8859-1"),"UTF-8");
			//如：13312341234
			//把请求参数打包成数组
			as.InsertOrder(uid, out_trade_no, subject, price, body, show_url, receive_name, receive_address, receive_zip, receive_phone, receive_mobile, cal.getNowTime().toString());
			Map<String, String> sParaTemp = new HashMap<String, String>();
			sParaTemp.put("service", "create_partner_trade_by_buyer");
			sParaTemp.put("partner", AlipayConfig.partner);
			sParaTemp.put("seller_email", AlipayConfig.seller_email);
			sParaTemp.put("_input_charset", AlipayConfig.input_charset);
			sParaTemp.put("payment_type", AlipayConfig.payment_type);
			sParaTemp.put("notify_url", AlipayConfig.notify_url);
			sParaTemp.put("return_url", AlipayConfig.return_url);
			sParaTemp.put("out_trade_no", out_trade_no);
			sParaTemp.put("subject", subject);
			sParaTemp.put("price", price);
			sParaTemp.put("quantity", quantity);
			sParaTemp.put("logistics_fee", logistics_fee);
			sParaTemp.put("logistics_type", logistics_type);
			sParaTemp.put("logistics_payment", logistics_payment);
			sParaTemp.put("body", body);
			sParaTemp.put("show_url", show_url);
			sParaTemp.put("receive_name", receive_name);
			sParaTemp.put("receive_address", receive_address);
			sParaTemp.put("receive_zip", receive_zip);
			sParaTemp.put("receive_phone", receive_phone);
			sParaTemp.put("receive_mobile", receive_mobile);
			//建立请求
			String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
			return sHtmlText;
		} catch(Exception e) {
			e.printStackTrace();
		}
		return "alipay";
	}
	*/

}
